package old.day20190320.shiwu;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * @author DingZhenYun
 * @create 2019-03-20 20:22
 */
//设置隔离级别
    //试事务的隔离级别 在 JDBC 程序中可以通过 Connection 的 setTransactionIsolation
// 来设置事务的隔离级别.
public class Test1 {
    public static void main(String[] args) {
        Test1 t=new Test1();
       t.testTransactionIsolationUpdate();
        //t.testTransactionIsolationRead();
    }

    private  void testTransactionIsolationRead() {
        String sql="SELECT balance from user where id=1";
        Integer b=getForValue(sql);
        System.out.println(b);
    }

    private static void  testTransactionIsolationUpdate() {
        Connection connection=null;
        try{
            connection=JDBCTools.getConnection();
            connection.setAutoCommit(false);
            String sql="update user set balance=balance-500 where id=1";
            update(connection,sql);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            JDBCTools.releaseDB(null,null,connection);
        }
    }
    // 返回某条记录的某一个字段的值 或 一个统计的值(一共有多少条记录等.)
    public <E> E getForValue(String sql, Object... args) {

        // 1. 得到结果集: 该结果集应该只有一行, 且只有一列
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        try {
            // 1. 得到结果集
            connection = JDBCTools.getConnection();
            System.out.println(connection.getTransactionIsolation());

//			connection.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
            //设置隔离级别
            connection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);

            preparedStatement = connection.prepareStatement(sql);

            for (int i = 0; i < args.length; i++) {
                preparedStatement.setObject(i + 1, args[i]);
            }

            resultSet = preparedStatement.executeQuery();

            if (resultSet.next()) {
                return (E) resultSet.getObject(1);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            JDBCTools.releaseDB(resultSet, preparedStatement, connection);
        }
        // 2. 取得结果

        return null;
    }
    public static void update(Connection conn,String sql,Object ... args){
        PreparedStatement preparedStatement=null;
        try {
            preparedStatement=conn.prepareStatement(sql);

            for(int i=0;i<args.length;i++){
                preparedStatement.setObject(i+1,args[i]);
            }
            preparedStatement.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            JDBCTools.releaseDB(null,preparedStatement,conn);
        }
    }
}
